package com.oasystem.utils;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import com.oasystem.domain.BackupFile;

public class BackupFilesUtils {
	public static List<BackupFile> getBackupFileList(int count) {
		List<File> sqlFileList = new ArrayList<File>();
		File f = new File(BackupConfigUtil.getParam("backuppath"));
		sqlFileList = Arrays.asList(f.listFiles());
		Collections.sort(sqlFileList, new Comparator<Object>() {
			public int compare(Object o1, Object o2) {
				if (new Date(((File) o1).lastModified()).after(new Date(
						((File) o2).lastModified()))) {
					return -1;
				} else {
					return 1;
				}
			}
		});

		List<File> subList = sqlFileList.subList(0,
				sqlFileList.size() > count ? count : sqlFileList.size());
		List<BackupFile> list = new ArrayList<BackupFile>();
		for (File tf : subList) {
			BackupFile bf = new BackupFile(
					new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(tf
							.lastModified()), tf.getName());
			list.add(bf);
		}

		return list;
	}
	
	public static void deleteBackupFiles(String date) throws Exception{
		if(date.trim().length()>10){
			throw new Exception("日期格式不正确");
		}
		File f = new File(BackupConfigUtil.getParam("backuppath"));
		List<File> sqlFileList = Arrays.asList(f.listFiles());
		SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");
		Date deadLine = sdf.parse(date);
		System.out.println(deadLine);
		for(File file : sqlFileList){
			Date current = new Date(file.lastModified());
			System.out.println(current);
			if(current.before(deadLine)){
				file.delete();
			}
		}
	}
	
	public static void main(String[] args) {
		try {
			BackupFilesUtils.deleteBackupFiles("2011-11-10");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
